//
//  LEEOAuthViewModel.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/15.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit

class LEEOAuthViewModel: NSObject {

    var userInfo : LEEUserInfoModel?
    
    static let shared = LEEOAuthViewModel()
    
    override init() {
        super.init()
        
        userInfo = getUserInfo()
    }
    
    var iconUrl : URL? {
    
        get{
        
            return URL(string: userInfo?.avatar_large ?? "")
        }
    
    }
    var access_token : String? {
    
        get{
        
            return userInfo?.access_token ?? ""
        }
    }
    
    
    
    //判断用户是否登录
    //计算型属性
    var isLogin : Bool {
    
        if userInfo?.access_token != nil && isExpires == false {
            
            return true
        }
        
        return false
    }
    //判断令牌是否过期
    var isExpires : Bool {
       
        if userInfo?.expires_date?.compare(Date()) == ComparisonResult.orderedAscending {
            
            return true
        }
        return false
    }
    
    
    ///获取access_token
    func getAccess_token(_ code : String , completion : @escaping (Bool) -> ()) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        
        LEEHTTPRequst.HTTPShared.request(method: .POST, urlString: urlStr, parameters: parameters) { (responseObject, error) in
            
            if error != nil {
      
                completion(false)
                return
            }
            
            //            print(responseObject)
            
            self.getUserInfo(dict: responseObject as! [String : Any?] , completion: completion)
            
        }
        
    }
    
    //获取用户信息
    private func getUserInfo(dict : [String : Any?] ,completion : @escaping (Bool) -> () ) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]
        let uid = dict["uid"]
        
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        
        LEEHTTPRequst.HTTPShared.request(method: .GET, urlString: urlStr, parameters: parameters){ (responseObject, error) in
            
            if error != nil {
     
                completion(false)
                return
            }
            
            var object = responseObject as! [String : Any]
            for (key , value) in dict {
                
                object[key] = value
            }
            
            self.userInfo = LEEUserInfoModel(dict: object)
            
            //            print(userInfo)
            
            self.saveUserInfo(self.userInfo!)
            
            completion(true)
        }
        
    }
    ///存档
    private func saveUserInfo(_ userModel: LEEUserInfoModel) {
        
        NSKeyedArchiver.archiveRootObject(userModel, toFile: path)
        print(path)
    }
    ///结档
    private func getUserInfo() -> LEEUserInfoModel?{
        
        print(path)
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? LEEUserInfoModel
        
    }
}
